package com.rolerealm.controller;

import com.rolerealm.domain.dto.ConversationDTOs.MessageRequest;
import com.rolerealm.service.LLMService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 简化流式对话控制器
 * 
 * @author RoleRealm Team
 * @version 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/streaming")
@RequiredArgsConstructor
public class SimpleStreamingController {

    private final LLMService llmService;
    private final ExecutorService executorService = Executors.newCachedThreadPool();

    /**
     * 简化流式发送消息
     */
    @PostMapping(value = "/conversations/{conversationId}/messages", 
                 produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamMessage(@PathVariable Long conversationId,
                                   @RequestHeader("Authorization") String authorization,
                                   @RequestBody MessageRequest request) {
        
        // 创建SSE发射器，设置超时时间为5分钟
        SseEmitter emitter = new SseEmitter(300_000L);
        
        // 异步处理流式响应
        executorService.submit(() -> {
            log.debug("开始异步处理流式响应，对话ID: {}", conversationId);
            try {
                // 使用普通LLM服务获取完整回复
                log.debug("调用LLM服务，内容: {}", request.getContent());
                String fullResponse = llmService.infer(request.getContent(), null);
                log.debug("LLM服务返回的完整回复: {}", fullResponse);
                
                if (fullResponse == null || fullResponse.trim().isEmpty()) {
                    log.warn("LLM服务返回空回复，使用默认回复");
                    fullResponse = "抱歉，我暂时无法回复您的消息。";
                }
                
                // 模拟流式输出，将回复分成小块发送
                String[] words = fullResponse.split("");
                log.debug("开始流式发送，总字符数: {}", words.length);
                for (int i = 0; i < words.length; i++) {
                    try {
                        // 发送单个字符
                        emitter.send(SseEmitter.event()
                            .data(words[i]));
                        log.debug("发送字符 {}: '{}'", i, words[i]);
                        
                        // 添加小延迟，模拟打字效果
                        Thread.sleep(50);
                        
                    } catch (IOException e) {
                        log.error("发送SSE数据失败", e);
                        emitter.completeWithError(e);
                        return;
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        emitter.completeWithError(e);
                        return;
                    }
                }
                
                // 发送完成信号
                try {
                    log.debug("发送完成信号");
                    emitter.send(SseEmitter.event()
                        .data("[DONE]"));
                    emitter.complete();
                    log.debug("流式发送完成");
                } catch (IOException e) {
                    log.error("发送SSE完成信号失败", e);
                    emitter.completeWithError(e);
                }
                
            } catch (Exception e) {
                log.error("流式消息处理失败", e);
                try {
                    emitter.send(SseEmitter.event()
                        .data("AI服务暂时不可用，请稍后重试"));
                    emitter.complete();
                } catch (IOException ioException) {
                    emitter.completeWithError(ioException);
                }
            }
        });
        
        // 设置完成和错误回调
        emitter.onCompletion(() -> log.debug("SSE连接完成，对话ID：{}", conversationId));
        emitter.onTimeout(() -> {
            log.warn("SSE连接超时，对话ID：{}", conversationId);
            emitter.complete();
        });
        emitter.onError(throwable -> log.error("SSE连接错误，对话ID：{}", conversationId, throwable));
        
        return emitter;
    }
}

